const Router = require('koa-router');
const router = new Router();
const tool = require("../../tools/tool");
const {db, Op, QueryTypes} = require("../../models/db");
const {toAccounted} = require("./base");
const { billCanEdit } = require("./base");
// 审核
router.post('/bill/toAccounted', async ctx => {
    // 审核
    let ids = ctx.request.body.ids
    let transType = ctx.request.body.transType
    let tenantId = ctx.user.tenantId
    if(transType === 190001) {
        let cards = await db.models['card'].findOne({
            where: {
                tenantId,
                id: ids[0]
            }
        })
        await billCanEdit(cards.billDate, tenantId)
        return await cardAccounted(ctx, ids);
    }
    else {
        return await toAccounted(ctx, ids);
    }
})
const cardAccounted = async 　(ctx, ids) => {
    let tenantId = ctx.user.tenantId
    for (let i = 0; i < ids.length; i++) {
        let model = await db.models['card'].findOne({
            where: {
                tenantId,
                id: ids[i]
            }
        })
        model.accountedBy = ctx.user.id
        model.accountedAt = tool.getTime()
        model.billState = 'accounted'
        await model.save()
        return ctx.suc('已审核')
    }
}

const detectHxAmount = async (tenantId, receiptId ) => {
    let sql = `
             select billNo, transType,arrears,hxAmount,nowCheck  from 
            (
                 select b.billNo,b.transType,b.arrears,nowCheck,hxAmount   
                 from (
                            select b.billId,sum(isnull(b.nowCheck,0) + isnull(b.yhAmount, 0)) nowCheck from
                            invoice a inner join invoice_receipt b on a.id=b.iid and a.id=${receiptId} and a.tenantId=${tenantId} and a.tenantId=b.tenantId 
                            group by b.billId, b.srcTransType
                        ) a inner join invoice b on a.billId=b.id
             ) a where 
			case when transType=150502 or transType=150602 then -nowCheck else nowCheck end > case when transType=150502 or transType=150602 then -(arrears-hxAmount) else(arrears-hxAmount) end 
        `
    let ret = await db.query(sql, {type: QueryTypes.SELECT})
    if(ret.length > 0) {
        throw Error(`【${ret[0].billNo}】 核销金额合计超过票据应收余额 `)
    }
}

module.exports = router;